#include<iostream>
using namespace std;
#include<queue>
int M;
int N;
const int MAX_N = 51;
string mp[MAX_N];
bool used[MAX_N][MAX_N];
bool vis[MAX_N][MAX_N];
typedef pair<int,int>  PII;
int dx[8] = { 0,0,1,-1,1,1,-1,-1};
int dy[8] = { 1,-1,0,0,1,-1,1,-1};

void bfs(int x,int y)
{
	queue<PII>st;
	st.push({ x,y });
	used[x][y] = true;
	while (st.size())
	{
		auto [a, b] = st.front();
		st.pop();
		for (int k = 0; k < 4; k++)
		{
			int newx = a + dx[k];
			int newy = b + dy[k];
			if (newx < 0 || newx >= M || newy < 0 || newy >= N || used[newx][newy] || mp[newx][newy] == '0')
				continue;
			st.push({ newx,newy });
			used[newx][newy]=true;
		}
		
	
	}

}
bool to_bfs(int x, int y)
{   
	for (int i = 0; i < M; i++)
	{
		for (int j = 0; j < N; j++)
		{

			vis[i][j] = false;
		}
	}




	queue<PII>st;
	st.push({ x,y });
  vis[x][y] = true;
	while (st.size())
	{
		auto [a, b] = st.front();
		st.pop();
		if (a == 0 || a == M - 1 || b == 0 || b == N - 1)return true;

		for (int k = 0; k < 8; k++)
		{
			int newx = a + dx[k];
			int newy = b + dy[k];
			if (newx < 0 || newx >= M || newy < 0 || newy >= N || vis[newx][newy] || mp[newx][newy] == '1')
				continue;
			st.push({ newx,newy });
			vis[newx][newy] = true;




		}
	

	}
	return false;



}
int main()
{
	int T;
	cin >> T;
	while (T--)
	{
		int count = 0;
		cin >> M >> N;
		for (int i = 0; i < M; i++)
		{
			cin >> mp[i];
			for (int j = 0; j < N; j++)
			{

				used[i][j] = false;

			}

		}
		for (int i = 0; i < M; i++)
		{
			for (int j = 0; j < N; j++)
			{
				if (!used[i][j] && mp[i][j] == '1')
				{
					bfs(i, j);
					if (to_bfs(i, j)) count++;




				}

			}
		}
		cout << count << " ";
		







	}
	





}